package edu.xidian.onlinedocument.controller.configuration;

import edu.xidian.onlinedocument.handler.interceptor.CheckTokenInterceptor;
import edu.xidian.onlinedocument.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 *
 * 可参考这篇博客：https://my.oschina.net/bianxin/blog/2876640
 * 以及路径的配置：https://www.cnblogs.com/zktww/p/11550891.html
 */
@Configuration
public class WebConfigurer implements WebMvcConfigurer {

    private final UserService userService;

    @Autowired
    public WebConfigurer(UserService userService) {
        this.userService = userService;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // 拦截所有请求
        registry.addInterceptor(CheckTokenInterceptor()).addPathPatterns("/**");
    }

    // 解决跨域问题
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        /*
        addMapping：允许以映射
        allowedHeaders：允许以请求头
        allowedMethods：允许以请求方式
        allowedOrigins：允许以域名访问
        allowCredentials：允许携带cookie参数
        */
        registry.addMapping("/**")
                .allowedHeaders("*")
                .allowedMethods("*")
                .allowedOrigins("*")
                .allowCredentials(false);
    }

    @Bean
    public CheckTokenInterceptor CheckTokenInterceptor() {
        return new CheckTokenInterceptor(userService);
    }
}
